package service

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"io"
	"net/http"
	"os"
	"project-deploy-service/models"
	"project-deploy-service/utils"
)

type historyService struct{}

var HistoryService historyService

func (fu *historyService) List(c *gin.Context) {
	history := readHistory()
	c.JSON(http.StatusOK, history)
}
func (fu *historyService) Insert(history models.HistoryModel) {
	var historyList = readHistory()
	history.Uuid = uuid.New()
	historyList = append(historyList, history)
	err := utils.FileUtil.Write("conf/history.json", historyList)
	if err != nil {
		return
	}

}
func (fu *historyService) Delete(c *gin.Context) {
	var slice []models.HistoryModel
	var historyList = readHistory()
	UUID := c.PostForm("uuid")
	parsedUUID, err := uuid.Parse(UUID)
	if err != nil {
		fmt.Println("Error parsing UUID:", err)
		return
	}
	for _, historyItem := range historyList {
		if historyItem.Uuid != parsedUUID {
			slice = append(slice, historyItem)
		} else {
			err := os.RemoveAll(historyItem.Path)
			if err != nil {
				fmt.Println("Error deleting file:", err)
				return
			}
		}
	}
	err = utils.FileUtil.Write("conf/history.json", slice)
	if err != nil {
		fmt.Println("Error deleting history:", err)
		c.String(http.StatusBadRequest, fmt.Sprintf("删除失败: %s", err.Error()))
	}
	c.String(http.StatusOK, "删除成功!")
}

// Rollback 回滚
func (fu *historyService) Rollback(c *gin.Context) {
	var historyProject models.HistoryModel
	UUID := c.PostForm("uuid")
	parsedUUID, err := uuid.Parse(UUID)
	if err != nil {
		fmt.Println("Error parsing UUID:", err)
		return
	}
	var historyList = readHistory()
	for _, historyItem := range historyList {
		if historyItem.Uuid == parsedUUID {
			historyProject = historyItem
		}
	}
	config := utils.FileUtil.LoadConfig()
	list := config.ProjectList
	for _, project := range list {
		if historyProject.Name == project.Filename {
			err := os.RemoveAll(project.Path)
			if err != nil {
				c.String(http.StatusBadRequest, fmt.Sprintf("Error renaming file: %s", err.Error()))
				return
			}
			err = os.Rename(historyProject.Path, project.Path)
			if err != nil {
				c.String(http.StatusBadRequest, fmt.Sprintf("Error renaming file: %s", err.Error()))
				return
			}
			c.String(http.StatusOK, "回滚成功!")
		}
	}
}

func readHistory() []models.HistoryModel {
	var history []models.HistoryModel
	file, err := os.Open("conf/history.json")
	if err != nil {
		fmt.Println("Error opening JSON file:", err)
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			return
		}
	}(file)
	bytes, err := io.ReadAll(file)
	if err != nil {
		fmt.Println("Error reading JSON file:", err)
	}

	if err := json.Unmarshal(bytes, &history); err != nil {
		fmt.Println("Error parsing JSON file:", err)
	}
	return history
}
